import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_map_demo/configs/poi_search_base_config.dart';
import 'package:t3_data_service/biz_data_source/map/address/poi_search/poi_search.dart';
import 'package:t3_foundation/t3_foundation.dart';
import 'package:uikit/uikit.dart';

import '../../view_model/poi_search_cell_view_model.dart';

class T3POICell extends StatelessWidget {
  final POISearchBaseConfig config;
  final String? keyword;
  final POISearchCellViewModel vm;
  final ValueChanged<int> onSelectSubPoi;
  final ValueChanged<POISearchCellViewModel> clickShareButton;

  const T3POICell(
      {Key? key,
      this.keyword,
      required this.config,
      required this.vm,
      required this.onSelectSubPoi,
      required this.clickShareButton})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(left: 12, right: 12, bottom: 0, top: 16),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: vm.corner ?? const BorderRadius.all(Radius.zero)),
      child: Column(
        children: [
          Container(
            decoration: const BoxDecoration(color: Colors.white),
            child: _buildMain(context),
          ),
          if (vm.bottomTags.isNotEmpty)
            Padding(
              padding: const EdgeInsets.only(left: 25.0),
              child: bottomTags(),
            ),
          if (vm.subPOIs.isNotEmpty) ...[
            const SizedBox(
              height: 16,
            ),
            _buildSubCells(context, vm.style, vm.subPOIs),
          ],
          vm.showDivider
              ? Container(
                  height: 0.5,
                  margin: const EdgeInsets.only(
                    top: 16,
                  ),
                  color: const Color(0xFFEFF1F5),
                )
              : const SizedBox(
                  height: 16,
                )
        ],
      ),
    );
  }

  _buildShareButton() {
    return T3GestureDetector(
      onTap: () => clickShareButton(vm),
      child: Container(
        width: 47,
        height: 20,
        decoration: BoxDecoration(
          border: Border.all(color: LucyColors.lucy_B7BECC, width: 0.5),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Row(
          children: [
            const SizedBox(
              width: 2,
            ),
            T3Image.t3assets(T3AssetsName.icon_share_dest),
            const SizedBox(
              width: 2,
            ),
            const Text(
              '分享',
              style: TextStyle(
                  color: LucyColors.lucy_02102A,
                  fontSize: 10,
                  fontWeight: LucyFonts.regular),
            )
          ],
        ),
      ),
    );
  }

  Widget _buildMain(BuildContext context) {
    var distanceWidth = calculateTextWidth(context, vm.distanceText, 12);
    var titleWidth = calculateTextWidth(context, vm.poiName, 14) + 4;
    var maxTitleWidth = MediaQuery.of(context).size.width -
        24 -
        31 -
        topTagsWidth(context) -
        distanceWidth -
        24 -
        8;
    var showTitleWidth = min(titleWidth, maxTitleWidth);

    var detailWidth = calculateTextWidth(context, vm.poiAddress, 12);
    var maxDetailWidth = MediaQuery.of(context).size.width - 24 - 31 - 47 - 24;
    var showDetailWidth = min(detailWidth, maxDetailWidth);
    return Row(
      children: [
        SizedBox(
          width: 21,
          height: 21,
          child: T3Image.t3assets(T3AssetsNameString(vm.logoName)),
        ),
        const SizedBox(width: 10),
        Flexible(
          flex: 1,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(
                    width: showTitleWidth,
                    child: RichTextWithKeyword(
                      text: vm.poiName,
                      keyword: keyword ?? '',
                      normalStyle: const TextStyle(
                        color: LucyColors.lucy_02102A,
                        fontSize: LucyFonts.size_14,
                        fontWeight: LucyFonts.semi_bold,
                      ),
                      highlightStyle: const TextStyle(
                        color: LucyColors.lucy_FA6400,
                        fontSize: LucyFonts.size_14,
                        fontWeight: LucyFonts.semi_bold,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  if (vm.topTags.isNotEmpty) topTags(context),
                  const Expanded(
                    child: SizedBox(
                      width: 8,
                    ),
                  ),
                  if (vm.distanceText.isNotEmpty)
                    Text(
                      vm.distanceText,
                      textDirection: TextDirection.rtl,
                      style: const TextStyle(
                          color: LucyColors.lucy_A1A6B3,
                          fontWeight: LucyFonts.regular,
                          fontSize: LucyFonts.size_12),
                      maxLines: 1,
                    ),
                ],
              ),
              vm.showShareButton
                  ? Row(
                      children: [
                        SizedBox(
                          width: showDetailWidth,
                          child: _buildDetailText(),
                        ),
                        const Expanded(child: SizedBox()),
                        _buildShareButton(),
                      ],
                    )
                  : _buildDetailText(),
            ],
          ),
        )
      ],
    );
  }

  Text _buildDetailText() {
    return Text(
      vm.poiAddress,
      style: const TextStyle(
          color: LucyColors.lucy_A1A6B3,
          fontWeight: LucyFonts.regular,
          fontSize: LucyFonts.size_12),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }

  Widget _buildSubCells(
      BuildContext context, T3POIStyle style, List<SubPOIModel> list) {
    double subCellSpace = 10;
    int countPerLine = 2;
    int totalCount = min(6, list.length);
    double cellWidth =
        (MediaQuery.of(context).size.width - 32 - 20 - subCellSpace) / 2;
    double cellHeight = style.subCellHeight();
    double radio = cellWidth / cellHeight;
    double totalHeight() {
      final cellLineCount = (totalCount / countPerLine).ceilToDouble();
      return style.subCellHeight() * cellLineCount +
          subCellSpace * (cellLineCount - 1) +
          1;
    }

    int percent(double hotPercent) {
      return (hotPercent * 100).truncate();
    }

    return Container(
        width: MediaQuery.of(context).size.width,
        height: totalHeight(),
        decoration: const BoxDecoration(color: Colors.white),
        child: GridView.builder(
            padding: EdgeInsets.zero,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: countPerLine,
                crossAxisSpacing: subCellSpace,
                mainAxisSpacing: subCellSpace,
                childAspectRatio: radio),
            itemCount: totalCount,
            itemBuilder: (context, index) {
              var sname = list[index].sname ?? '';
              var size = calculateTextWidth(context, sname, 12);
              var sWidth = size;
              var percentText = '';
              if (config.showHotPercent &&
                  list[index].hotPercent != null &&
                  list[index].hotPercent! > 0) {
                percentText = "${percent(list[index].hotPercent!)}%选择";
              }
              var pSize = calculateTextWidth(context, percentText, 10) + 2;
              if (pSize + size + 8 > cellWidth) {
                var maxWidth = cellWidth - 6;
                if (percentText.isNotEmpty) {
                  maxWidth = maxWidth - 6 - pSize;
                }
                if (maxWidth < cellWidth * 0.32) {
                  maxWidth = cellWidth * 0.32;
                  pSize = cellWidth * 0.7 - 8;
                }
                sWidth = min(maxWidth, size);
              }
              return T3GestureDetector(
                onTap: () {
                  onSelectSubPoi(index);
                },
                child: Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      border: Border.all(
                          width: 0.5, color: const Color(0xFFE9EBF0)),
                      borderRadius: const BorderRadius.all(Radius.circular(8))),
                  height: style.subCellHeight(),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const SizedBox(
                        width: 4,
                      ),
                      SizedBox(
                        width: sWidth,
                        child: Text(
                          sname,
                          style: const TextStyle(
                              fontSize: 12,
                              color: LucyColors.lucy_02102A,
                              overflow: TextOverflow.ellipsis),
                          maxLines: 1,
                        ),
                      ),
                      // 热度
                      const SizedBox(
                        width: 3,
                      ),
                      if (config.showHotPercent &&
                          list[index].hotPercent != null &&
                          list[index].hotPercent! > 0)
                        SizedBox(
                          width: pSize,
                          child: Text(
                            "${percent(list[index].hotPercent!)}%选择",
                            style: const TextStyle(
                                fontSize: 10,
                                color: Color(0xFF00AD59),
                                overflow: TextOverflow.ellipsis),
                            maxLines: 1,
                          ),
                        ),
                    ],
                  ),
                ),
              );
            }));
  }

  Widget topTags(BuildContext context) {
    List<T3POITag> tags = vm.topTags;
    if (tags.length > 2) {
      tags = tags.sublist(0, 2);
    }
    return Row(
      children: _tags(tags),
    );
  }

  double topTagsWidth(BuildContext context) {
    List<T3POITag> tags = vm.topTags;
    if (tags.isEmpty) {
      return 0;
    }
    if (tags.length > 2) {
      tags = tags.sublist(0, 2);
    }
    var w = 0.0;
    for (var element in tags) {
      w += calculateTextWidth(context, element.content, 10);
    }
    return w + tags.length * 8;
  }

  double calculateTextWidth(
      BuildContext context, String text, double fontSize) {
    if (text.isEmpty) {
      return 0;
    }
    return StringUtils.calculateTextSize(context, text, fontSize: fontSize)
        .width;
  }

  Widget bottomTags() {
    return Row(
      children: _tags(vm.bottomTags),
    );
  }

  List<Widget> _tags(List<T3POITag> tags) {
    return tags.map((e) {
      return Container(
        height: 16,
        margin: const EdgeInsets.only(left: 4),
        padding: const EdgeInsets.only(left: 2, right: 2),
        decoration: BoxDecoration(
            color: e.backgroundColor,
            borderRadius: const BorderRadius.all(Radius.circular(4))),
        child: Center(
          child: Text(
            e.content,
            style: TextStyle(color: e.textColor, fontSize: 10),
          ),
        ),
      );
    }).toList();
  }
}
